<%@ page language="java" contentType="text/html; charset=UTF-8"  pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<c:set var="ctx" value="${pageContext.request.contextPath}" />

<ul class="breadcrumb panel">
    <li><a href="javascript:backMainFun();"><i class="fa fa-home"></i> 首页</a></li>
    <li class="active">用户管理</li>
</ul>

<div class="panel">
    <div class="panel-body">
        <form action="" onsubmit="return false;">
            <div class="row">
                <div class="col-xs-3">
                    <div class="form-group marBN">
                        <div class="iconic-input">
                            <i class="fa fa-user"></i>
                            <input type="text" class="form-control" id="query_user_name" name="query_user_name" placeholder="按用户名查找">
                        </div>
                    </div>
                </div>
                <div class="col-xs-3">
                    <div class="form-group marBN">
                        <div class="iconic-input">
                            <i class="fa fa-sign-in"></i>
                            <input type="text" class="form-control"  id="query_login_name" name="query_login_name" placeholder="按登录名查找">
                        </div>
                    </div>
                </div>
                <div class="col-xs-3">
                    <div class="form-group marBN">
                        <div class="iconic-input">
                            <i class="fa fa-sitemap"></i>
                            <input type="text" class="form-control" id="query_org_name" name="query_org_name" placeholder="按组织机构查找">
                        </div>
                    </div>
                </div>
                <div class="col-xs-3">
                    <button id="searchBtn" type="submit" class="btn btn-success"><i class="glyphicon glyphicon-search"></i> 查找</button>
                    <button type="reset" class="btn btn-warning"><i class="fa fa-trash-o"></i> 清空</button>
                </div>
            </div>
        </form>
    </div>
</div>

<div class="panel">
    <header class="panel-heading">
        用户列表
    </header>
    <div class="panel-body">
        <div id="toolbar">
            <a href="javascript:loadFun('/user/toUserAdd');" class="btn btn-info"><i class="glyphicon glyphicon-plus"></i> 新增用户</a>
        </div>
        <table id="table1"
               data-toggle="table"
               data-classes="table table-hover"
               data-sort-order="asc"
               data-method="get"
               data-data-type="json"
               data-pagination="true"
               data-show-columns="true"
               data-minimum-count-columns="3"
               data-page-size="10"
               data-locale="zh-CN"
               data-striped="true"
        ></table>
    </div>
</div>
<div class="modal fade" id="orgModal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
                <h4 class="modal-title">选择组织机构</h4>
            </div>
            <div class="modal-body">
                <div class="container-fluid" style="background: #f8f8f8;border-radius: 3px;max-height: 500px;overflow: auto">
                    <input type="hidden" id="ztree_user"/>
                    <div id="treeApp" class="ztree"></div>
                </div>

            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal"><i class="glyphicon glyphicon-off"></i> 关闭</button>
                <button id="checkorgOk" type="button" class="btn btn-primary"><i class="glyphicon glyphicon-ok"></i> 确定</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<div class="modal fade" id="pmMal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">可视范围</h4>
            </div>
            <div class="modal-body">
                <input type="hidden" id="pm_user" value="">
                <select class="form-control" id="permission" name="permission" placeholder="请选择可视范围">
                    <c:forEach var="t" items="${pmList}">
                        <option value="${t.code}">${t.value}</option>
                    </c:forEach>
                </select>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal"><i class="glyphicon glyphicon-off"></i> 关闭</button>
                <button id="subPmBtn" type="button" class="btn btn-primary"><i class="glyphicon glyphicon-ok"></i> 确定</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->
<div class="modal fade" id="fjsMal">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">赋角色</h4>
            </div>
            <div class="modal-body">
                <input type="hidden" id="user_id_hide" value="">
                <div class="container icheck" id="checkBox">
                    
                </div>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal"><i class="glyphicon glyphicon-off"></i> 关闭</button>
                <button id="subfjsBtn" type="button" class="btn btn-primary"><i class="glyphicon glyphicon-ok"></i> 确定</button>
            </div>
        </div><!-- /.modal-content -->
    </div><!-- /.modal-dialog -->
</div><!-- /.modal -->


<script>

    $('#searchBtn').click(function(){
        $("#table1").bootstrapTable('refreshOptions',
                {
                    pagination: true,
                    dataShowToggle: true,
                    url: "${ctx}/user/getUserList",
                    queryParams: function (params) {
                        return $.extend({}, params, {
                            query_user_name: $('#query_user_name').val(),
                            query_login_name: $('#query_login_name').val(),
                            query_org_name: $('#query_org_name').val()
                        });
                    }
                });
    });


    $("#table1").bootstrapTable({
        contentType: "application/x-www-form-urlencoded",
        method: 'post',
        sidePagination: 'server',
        toolbar: '#toolbar',
        pagination: true,
        dataShowToggle: true,
        url:"${ctx}/user/getUserList",
        columns: [
            {
                field: 'num',
                title: '序号',
                formatter:function (value, row, index) {
                    if($('.pagination').find('li.active').find('a').text()){
                        var numbers = parseInt([parseInt($('.pagination').find('li.active').find('a').text())-1]* parseInt($('.page-size').text()) )+ parseInt(index+1);
                        return [
                            numbers
                        ].join('') ;
                    }else{
                        return [
                            index+1
                        ].join('') ;
                    }

                }
            }, {
                field: 'user_name',
                title: '用户名'
            },{
                field: 'login_name',
                title: '登录名'
            },{
                field: 'id_card',
                title: '身份证号'
            },{
                field: 'dept_name',
                title: '组织机构'
            },{
                field: 'phone',
                title: '联系电话'
           },{
                field: 'email',
                title: '邮箱'
//            },{
//                field: 'value',
 //               title: '可视范围'
            },{
                field: 'user_id',
                title: '操作',
                formatter:option
            }]
    });
    function option(value,row){

        return [
//            '<button class="btn btn-xs btn-primary" onclick="orgFun(\''+value+'\',\''+row.org_id+'\')"><i class="fa fa-sitemap"></i> 组织机构</button>&nbsp;&nbsp;',
//            '<button class="btn btn-xs btn-info" onclick="pmFun(\''+value+'\',\''+row.permission+'\')"><i class="fa fa-eye"></i> 可视范围</button>&nbsp;&nbsp;',
            '<button class="btn btn-xs btn-success" onclick="fjsFun(\''+value+'\',\''+row.dept_name+'\')"><i class="fa fa-user-md"></i> 赋角色</button>&nbsp;&nbsp;',
            '<button class="btn btn-xs btn-warning" onclick="updateFun(\''+value+'\')"><i class="glyphicon glyphicon-pencil"></i> 修改</button>&nbsp;&nbsp;',
            '<button class="btn btn-xs btn-success" onclick="resetPwdFun(\''+value+'\')"><i class="fa fa-unlock-alt"></i> 重置密码</button>&nbsp;&nbsp;',
           '<button class="btn btn-xs btn-danger" onclick="delFun(\''+value+'\')"><i class="glyphicon glyphicon-remove"></i> 删除</button>',
        ].join('');
    }


    function pmFun(user_id,permission){
        $('#pm_user').val(user_id);
        $('#permission').val(permission);
        $('#pmMal').modal('show');
    }
    $('#subPmBtn').click(function(){
        $.ajax({
            url: "${ctx}/user/updatePm",
            type: 'post',
            data:{user_id:$('#pm_user').val(),permission:$('#permission').val()},
            success: function (data) {
                zConfirmHide();
                if(data.success){
                    $("#table1").bootstrapTable('refresh',{url:"${ctx}/user/getUserList"});
                    setTimeout(function(){
                        zAlert(data.msg)
                    },100);
                }else{
                    setTimeout(function(){
                        zAlert(data.msg)
                    },100);
                }
            }
        });
        $('#pmMal').modal('hide');
    });



    //初始化树并且请求树的数据
    var zNodes;
    var zTreeObj;
    var setting = {
        view: {
            showLine: false,
            expandSpeed: "fast"
        },
        check:{
            enable: true,
            chkStyle: "radio",
            radioType: "all"
        }
    };
    $.ajax({
        url: "${ctx}/org/getOrgTree",
        type: 'post',
        success: function (data) {
            zNodes=data;
            if(zNodes[0]){
                zNodes[0].open=true;
            }
            return zNodes;
        }
    });




    //显示树
    function orgFun(user_id,org_id){
        $('#ztree_user').val(user_id);
        parentId=[];

        zTreeObj = $.fn.zTree.init($("#treeApp"), setting, zNodes);

        var node = zTreeObj.getNodeByParam("id", org_id, null);
        TraParOpen(node);

        TraversalObject(zNodes[0],org_id,parentId);//调用递归算法

        zTreeObj = $.fn.zTree.init($("#treeApp"), setting, zNodes);


        $('#orgModal').modal('show');
    }

    var parentId=[];  //需要展开的id的数组

    //获取需要展开的id，集合成数组
    function TraParOpen(node) {
        var nodeParent;//父节点
        if (node) {
            nodeParent = node.getParentNode();
            if(nodeParent && nodeParent.isParent){
                parentId.push(nodeParent.id);
                TraParOpen(nodeParent);
            }else{
                return;
            }
        }
    }

    //递归算法
    function TraversalObject(obj,id,parentId){
        for (var a in obj) {
            if(a=="id"){
                if(parentId.indexOf(obj[a])>=0){
                    obj.open=true;
                }else{
                    obj.open=false;
                };
                if(obj[a]==id){
                    obj.checked=true;

                }else {
                    obj.checked=false;
                };
            };
            if (typeof (obj[a]) == "object"){
                TraversalObject(obj[a],id,parentId); //递归遍历
            }
        }
    }


    $('#checkorgOk').click(function(){
        var nodes=zTreeObj.getCheckedNodes(true);
        $.ajax({
            url: "${ctx}/user/updateOrg",
            type: 'post',
            data:{user_id:$('#ztree_user').val(),org_id:nodes[0].id,org_name:nodes[0].name},
            success: function (data) {
                zConfirmHide();
                if(data.success){
                    $("#table1").bootstrapTable('refresh',{url:"${ctx}/user/getUserList"});
                    setTimeout(function(){
                        zAlert(data.msg)
                    },100);
                }else{
                    setTimeout(function(){
                        zAlert(data.msg)
                    },100);
                }
            }
        });
        $('#orgModal').modal('hide');
    });

    function fjsFun(value,orgName){
        if(orgName == "undefined" || orgName==null || orgName==""){
            zAlert("请先给用户配置组织机构！");
            return false;
        }
        $('#fjsMal').modal('show');

        $('#user_id_hide').val(value);

        var checkBox = $('#checkBox');
        checkBox.empty();
        $.post("${ctx}/user/selectRoles?user_id="+value,function(data){
            console.log(data);

            for(var i=0;i<data.roles.length;i++){
                if(data.userRoles.length>0){
                    var checkString='<div class="square-blue single-row">' +
                            '<div class="checkbox">' +
                            '<label><input  class="role-check" name="role_id" ';
                            for(var j=0;j<data.userRoles.length;j++) {
                                if(data.roles[i].role_id==data.userRoles[j].roleId){
                                    checkString+=' checked  ';
                                        continue;
                                }
                            }
                    checkString+=' type="checkbox" value="' + data.roles[i].role_id + '">' + data.roles[i].name + '</label>' +
                            '</div></div>';
                    checkBox.append(checkString);
                }else{
                    checkBox.append('<div class="square-blue single-row">' +
                            '<div class="checkbox">' +
                            '<label><input  class="role-check" name="role_id" type="checkbox" value="' + data.roles[i].role_id + '">' + data.roles[i].name + '</label>' +
                            '</div>' +
                            '</div>');
                }

            }

            $('.role-check').iCheck({
                        checkboxClass: 'icheckbox_square-blue',
                        radioClass: 'iradio_square',
                        increaseArea: '20%' // optional
            });

        },"json");

    }

    $('#subfjsBtn').click(function() {
        var roleCheck = document.getElementsByClassName('role-check');
        var roleVal='';
        for(var i=0;i<roleCheck.length;i++){
            if(roleCheck[i].checked){
                roleVal+=roleCheck[i].value+',';
            }
        }
        $.post("${ctx}/user/configRoles?user_id="+$('#user_id_hide').val()+'&role_id='+roleVal,function(data){
            zAlert(data.msg);
            $('#fjsMal').modal('hide');
        });
    });


    function updateFun(value){
        loadFun("/user/toUserUpdate?user_id="+value);
    }

    function delFun(value) {
        zConfirm('确认删除？');
        confirmOk.click(function(){
            $.post("${ctx}/user/deleteUser?user_id="+value,function(data){
                zConfirmHide();
                if(data.success){
                    $("#table1").bootstrapTable('refresh',{url:"${ctx}/user/getUserList"});
                    setTimeout(function(){
                        zAlert(data.msg)
                    },100);
                }else{
                    setTimeout(function(){
                        zAlert(data.msg)
                    },100);
                }
            });
        });
    }

    function resetPwdFun(value){
        zConfirm('确认重置密码？');
        confirmOk.click(function(){
            $.post("${ctx}/user/resetUserPwd?user_id="+value,function(data){
                zConfirmHide();
                if (data.success) {
                    zAlert(data.msg)
                    loadFun("user/toUserIndex");
                } else {
                    zAlert(data.msg)
                }
            });

        });
    }

</script>